import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { usePermissionStore } from '@/stores/permission'
const Layout = () => import('@/layout/index.vue')

export const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [{
      path: 'home',
      component: () => import('@/views/index.vue'),
      meta: { title: '首页', icon: 'HomeFilled' },
    }]
  },
  {
    path: '/icons',
    component: Layout,
    children: [{
      path: '',
      component: () => import('@/views/icons/index.vue'),
      meta: { title: '图标', svg: 'icon', url: 'https://www.iconfont.cn', urlName: 'iconfont' },
    }]
  },
  {
    path: '/x6',
    component: Layout,
    children: [{
      path: 'mindmap',
      component: () => import('@/views/x6/mindmap.vue'),
      meta: { title: '思维导图', svg: 'mindmap', url: 'https://x6.antv.antgroup.com/examples', urlName: 'X6', style: { padding: 0 } },
    }]
  },
  {
    path: '/vue3',
    component: Layout,
    meta: { title: 'Vue3', svg: 'logo' },
    children: [{
      path: 'npm',
      component: () => import('@/views/npm/index.vue'),
      meta: { title: 'npm', url: 'https://www.npmjs.com/', urlName: 'npm' },
    }, {
      path: 'pinia',
      component: () => import('@/views/pinia/index.vue'),
      meta: { title: 'Pinia', url: 'https://pinia.vuejs.org/zh/', urlName: 'Pinia' },
    }, {
      path: 'router',
      component: () => import('@/views/router/index.vue'),
      meta: { title: 'Router', url: 'https://router.vuejs.org/zh/', urlName: 'Router' },
    }, {
      path: 'vue',
      component: () => import('@/views/vue/index.vue'),
      meta: { title: 'Vue', url: 'https://cn.vuejs.org', urlName: 'Vue' },
    }]
  },
]

export const asyncRoutes: RouteRecordRaw[] = []

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: constantRoutes,
})

// 全局前置守卫
router.beforeEach(() => {
  usePermissionStore().generateRoutes().then((accessRoutes: RouteRecordRaw[]) => {
    accessRoutes.forEach(route => {
      router.addRoute(route)
    })
  })
})

export default router
